from operator import itemgetter
from indexer import *
import string_operations as str_op
import heapq

class searchSort:
    def __init__(self):
        self.sortMethods={"Good Sort":self.goodSort,"Stupid Sort":self.stupidSort}
        self.printOptions={"Title":True,"Authors":True,"File Location":True,"Fit":True}
        self.reversed=False
        self.numResults=5
        self.wordcountweight=1
        self.consecutiveweight=5
        self.sortMethod = self.goodSort
        self.parameters={"Number of Results":self.numResults, "Weighting of Query Count in a File":self.wordcountweight,"Weighting for Consecutive Words":self.consecutiveweight}
        self.fit={}
        
    def search(self, documentList, query):
        self.fit.clear()
        for doc in documentList:
            self.fit[doc] = self.sortMethod(doc,query)
        self.arrangeResults(documentList)
        results = []
        for i in range(0,min(len(documentList),self.numResults)):
            results = results + self.getResults(documentList[i])
        return results
    
    def stupidSort(self,doc,querys):
        stemmedQuery = str_op.makeStemList(querys)
        return doc.getWordCount(stemmedQuery[0])
    
    def goodSort(self,doc,querys):
        querys=str_op.makeStemList(querys)
        count=0
        for i in range(0, len(querys)-1):
            thisquery=querys[i]
            nextquery=querys[i+1]
            thislocs=doc.getWordLocations(thisquery)
            nextlocs=doc.getWordLocations(nextquery)
            for j in thislocs:
                if j+1 in nextlocs:
                    count+=self.consecutiveweight
            count+=doc.getWordCount(thisquery)*self.wordcountweight
        count+=doc.getWordCount(querys[len(querys)-1])*self.wordcountweight
        return count
    
    def arrangeResults(self,documentList):
        documentList.sort(lambda x, y: self.fit[y]-self.fit[x])
        if self.reversed: documentList.reverse()
        
    def getResults(self,doc):
        results = []
        if self.printOptions["Title"] and not doc.input_title=="": 
            results.append(doc.input_title)
        if self.printOptions["Authors"] and not doc.input_authors=="":
            results.append("BY "+doc.input_authors)
        if self.printOptions["File Location"]:
            results.append(doc.getLocation())
        if self.printOptions["Fit"]: 
            results.append("Fit="+str(self.fit[doc]))
        results.append('\n')
        return results
        